import router  from 'umi/router';
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { fakeAccountLogin,  fakeLogOut, setUserCooike, removeUserCooike } from '../services/user';
// import { mqttClose } from '../services/mqtt';
import { reloadAuthorized } from '../utils/Authorized';


export default {
  namespace: 'login',

  state: {
    status: false,
    authcheck_id:null,
  },

  effects: {
    *accountSubmit({ payload }, { call, put, select }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });

      const status = yield select(state => state.login.status);
      if(!status){
        const response = yield call(fakeAccountLogin, payload);
        if(response){
          yield put({
            type: 'changeLoginStatus',
            payload: true,
          });
          yield call(setUserCooike,response.data);
          yield put({
            type: 'global/fetch_current_role',
            payload:(response.data.userInfo && response.data.userInfo.roleAuthority) || [],
          });
          yield put({
            type: 'changeSubmitting',
            payload: false,
          });
          reloadAuthorized();
          yield put(routerRedux.replace('/'));
          return false;
        }
      }

      // response &&  (
      //
      // )
      // response &&  router.push('/')
    },


    *logout(_, {call, put }) {
      yield call(fakeLogOut);
      yield call(removeUserCooike);
      yield put({
        type: 'changeLoginStatus',
        payload: false,
      });
      // yield call(mqttClose);
      reloadAuthorized();
      //yield put(router.push('/user/login'));
      window.location.href='/user/login';
    },

    *verification_code({ payload }, { call, put }) {
      const response = yield call(queryVerificationCode, payload);
      response &&  (
        yield put({
          type: 'changeAuthcheckId',
          payload: response.data,
        })
      )
    },

    *retrieve_psw({ payload }, { call, put }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(saveRetrievePsw, payload);
      response &&  (
        message.success('密码已修改，请重新登录！')
      )
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });

    },

  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload,
        // type: payload.type,
      };
    },
    changeAuthcheckId(state, { payload }) {
      return {
        ...state,
        authcheck_id: payload.authcheck_id,
      };
    },
    changeSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },
  },
};
